const http = require('http')
const querystring = require('querystring')

const server = http.createServer((req,res) => {
    const method = req.method
    const url = req.url
    const path =  url.split('?')[0]
    const query = querystring.parse(url.split('?')[1])
    //设置格式为JSON
    res.setHeader('Content-type','application/json')
    //返回的数据
    const data = {
       method,
       url,
       path,
       query
    }
    if(method === 'GET') {
        res.end(
          JSON.stringify(data)
        )
    }
    if(method === 'POST') {
        let postData = ''
        //接收数据   数据流的形式  每次有数据就触发，接收完之后就触发end事件结束
        req.on('data', chunk => {
            postData += chunk.toString()
        })
        req.on('end', () => {
            data.postData = postData
            // 返回
            res.end(
                JSON.stringify(data)
            )
        })
    }
       
    
})
server.listen(8000)
console.log('listen8000 ok')
